import { RequestConfig } from "umi";
// 日志
import { createLogger } from 'redux-logger'
import { message } from "antd"

import Cookies from 'js-cookie'
// dva的日志配置
export const dva = process.env.NODE_ENV === 'production' ? {} : {
  config: {
    // onAction: createLogger(),
    onError(e: Error) {
      // message.error(e.message,3);
    }
  }
}


// 网络请求配置
const baseUrl = process.env.NODE_ENV === 'production' ? 'https://creationapi.shbwyz.com' : '/proxyApi';
export const request: RequestConfig = {
  timeout: 100000,
  errorConfig: {

  },
  middlewares: [],
  // 请求拦截器
  requestInterceptors: [(url, options) => {
    let Authorization = Cookies.get('token')
    console.log(Authorization, 'Authorization...');
    if (Authorization) {
      //本地存储 header 上传
      // localStorage.setItem("header", JSON.stringify(`Bearer ${Authorization}`))
      options.headers = {
        ...options.headers,
        Authorization: `Bearer ${Authorization}`,
      };
    }
    return {
      url: `${baseUrl}${url}`,
      options,
    };
  }],
  // 响应拦截器
  responseInterceptors: [response => {
    // console.log(response);
    //清空cookie方法
    // function clearCookie() {
    //   var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    //   if (keys) {
    //     for (var i = keys.length; i--;) {
    //       document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString();//清除当前域名下的,例如：m.kevis.com
    //       document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString();//清除当前域名下的，例如 .m.kevis.com
    //       document.cookie = keys[i] + '=0;path=/;domain=kevis.com;expires=' + new Date(0).toUTCString();//清除一级域名下的或指定的，例如 .kevis.com
    //     }
    //   }
    //   console.log('已清除');
    // }

    if (response.statusText === 'Unauthorized') {
      window.location.href = '/login'
      // clearCookie()
    }

    const codeMaps: { [key: number]: string } = {
      400: '错误的请求',
      403: '禁止访问',
      404: '找不到资源',
      500: '服务器内部错误',
      502: '网关错误。',
      503: '服务不可用，服务器暂时过载或维护。',
      504: '网关超时。',
    };
    if (Object.keys(codeMaps).indexOf(String(response.status)) !== -1) {
      // message.error({
      //   content: codeMaps[response.status],
      // });
    }
    return response;
  }],
};
